package cn.zptc.web;

import cn.zptc.dao.impl.FavoriteDaoImpl;
import cn.zptc.entity.Favorite;
import cn.zptc.service.FavoriteService;
import cn.zptc.service.impl.FavoriteServiceImpl;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/client/addFavorite")
public class AddFavoriteServlet extends HttpServlet {

    private FavoriteService favoriteService;

    @Override
    public void init() throws ServletException {
        super.init();

        favoriteService = new FavoriteServiceImpl(new FavoriteDaoImpl());
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader reader = req.getReader();
        String s = reader.readLine();
        Favorite favorite = JSON.parseObject(s, Favorite.class);
        try {
            int i = favoriteService.addFavorite(favorite);
            if(i==-1){
                resp.getWriter().write("fail");
            }else {
                resp.getWriter().write("success");
            }
        } catch (SQLException e) {
            resp.getWriter().write("success");
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
